package com.j3.db;

import java.io.Serializable;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

public class Db implements Serializable{
	
	private static final long serialVersionUID = 2985122886855120916L;
	private int dbId;
	private int serverId;
	private String dbName;
	private String serverName;
	private int port;
	private String ip;
	private String userName;
	private String password;
	private ServerType serverType;
	private Properties properties = new Properties();
	private String driverUrl;
	
	public Db() {
	}
	
	public Db(int dbId) {
		this.dbId = dbId;
	}
	
	public int getDbId() {
		return dbId;
	}

	public void setDbId(int dbId) {
		this.dbId = dbId;
	}

	public int getServerId() {
		return serverId;
	}

	public void setServerId(int serverId) {
		this.serverId = serverId;
	}

	public String getDbName() {
		return dbName;
	}

	public void setDbName(String dbName) {
		this.dbName = dbName;
	}

	public String getServerName() {
		return serverName;
	}

	public void setServerName(String serverName) {
		this.serverName = serverName;
	}

	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}

	public String getIp() {
		return ip;
	}

	public void setIp(String ip) {
		this.ip = ip;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public ServerType getServerType() {
		return serverType;
	}

	public void setServerType(ServerType serverType) {
		this.serverType = serverType;
	}
	
	public void setServerType(int typeId) {
		this.serverType = ServerType.getServerType(typeId);
	}

	public void setProperties(Properties properties) {
		this.properties = properties;
	}

	public Properties getProperties() {
		return properties;
	}

	public String getDriverUrl() {
		if (driverUrl == null) {
			driverUrl = serverType.getDriverUrl(this);
		}
		return driverUrl;
	}
	
	public Connection getConnection() throws ClassNotFoundException, SQLException {
		if(properties == null) {
			properties = new Properties();
		}
		Class.forName(serverType.getDriverClass());
		DriverManager.setLoginTimeout(10);
		properties.put("user", userName);
		properties.put("password", password);
		return DriverManager.getConnection(getDriverUrl(), properties);
	}
}
